﻿Imports Microsoft.VisualBasic
Imports Infragistics.WebUI.UltraWebGrid
Imports System.IO
Imports NPOI.HSSF.UserModel
Imports NPOI.SS.Util
Imports NPOI.SS.UserModel

Public Class uLMS_CommonFunction

#Region "分页"
    Shared Function FirstPage() As Integer
        FirstPage = 1
    End Function


    Shared Function LastPage(ByVal TotalPage As Integer, ByRef strInfo As String) As Integer
        If TotalPage < 1 Then
            strInfo = "总页数小于1"
            LastPage = -1
            Exit Function
        End If
        LastPage = TotalPage
    End Function

    Shared Function NextPage(ByVal CurrentPage As Integer, ByVal TotalPage As Integer, ByRef strInfo As String) As Integer
        If TotalPage < 1 Then
            strInfo = "总页数小于1"
            NextPage = -1
            Exit Function
        End If
        If CurrentPage < 1 Then
            strInfo = "当前页数小于1"
            NextPage = -1
            Exit Function
        End If

        Dim intNextPage As Integer = CurrentPage + 1
        If intNextPage > TotalPage Then
            NextPage = TotalPage
            Exit Function
        End If
        NextPage = intNextPage

    End Function


    Shared Function PrevPage(ByVal CurrentPage As Integer, ByVal TotalPage As Integer, ByRef strInfo As String) As Integer
        If TotalPage < 1 Then
            strInfo = "总页数小于1"
            PrevPage = -1
            Exit Function
        End If
        If CurrentPage < 1 Then
            strInfo = "当前页数小于1"
            PrevPage = -1
            Exit Function
        End If

        Dim intPrevPage As Integer = CurrentPage - 1
        If intPrevPage < 1 Then
            PrevPage = 1
            Exit Function
        End If
        PrevPage = intPrevPage
    End Function

    Shared Function GoPage(ByVal CurrentPage As Integer, ByVal TotalPage As Integer, ByRef strInfo As String) As Integer
        If TotalPage < 1 Then
            strInfo = "总页数小于1"
            GoPage = -1
            Exit Function
        End If
        If CurrentPage < 1 Then
            strInfo = "跳转页数小于1"
            GoPage = 1
            Exit Function
        End If

        If CurrentPage > TotalPage Then
            strInfo = "跳转页大于总页数"
            GoPage = -1
            Exit Function
        End If
        GoPage = CurrentPage
    End Function
#End Region


#Region "通用控件处理方法"
    ''' <summary>
    ''' 验证数字格式 正整数
    ''' create:YangSJ
    ''' </summary>
    ''' <param name="txtInteger">文本控件</param>
    ''' <param name="isInquiry">是否必填</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Shared Function ValidateInteger(ByVal txtInteger As Camstar.WebClient.FormsBuilder.WebControls.TextBox, ByVal isInquiry As Boolean, ByRef strMessage As String) As Boolean
        Dim strInteger As String = txtInteger.TextControl.Text
        Dim intStr As Integer = 0
        ValidateInteger = False
        If String.IsNullOrWhiteSpace(strInteger) Then
            If isInquiry Then
                strMessage = String.Format("请输入{0}", txtInteger.Text)
            Else
                ValidateInteger = True
            End If
            Exit Function
        End If

        If Not Integer.TryParse(strInteger, intStr) Then
            strMessage = String.Format("{0}应为数字", txtInteger.Text)
            Exit Function
        End If

        If intStr < 1 Then
            strMessage = String.Format("{0}应大于零", txtInteger.Text)
            Exit Function
        End If
        ValidateInteger = True
    End Function


    ''' <summary>
    ''' 验证数字格式 整数（包含0）
    ''' create:Duht 2020-10-16
    ''' </summary>
    ''' <param name="txtInteger">文本控件</param>
    ''' <param name="isInquiry">是否必填</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Shared Function ValidateIntegerAndZero(ByVal txtInteger As Camstar.WebClient.FormsBuilder.WebControls.TextBox, ByVal isInquiry As Boolean, ByRef strMessage As String) As Boolean
        Dim strInteger As String = txtInteger.TextControl.Text
        Dim intStr As Integer = 0
        ValidateIntegerAndZero = False
        If String.IsNullOrWhiteSpace(strInteger) Then
            If isInquiry Then
                strMessage = String.Format("请输入{0}", txtInteger.Text)
            Else
                ValidateIntegerAndZero = True
            End If
            Exit Function
        End If

        If Not Integer.TryParse(strInteger, intStr) Then
            strMessage = String.Format("{0}应为数字", txtInteger.Text)
            Exit Function
        End If

        If Integer.Parse(strInteger) < 0 Then
            strMessage = String.Format("{0}不能小于零", txtInteger.Text)
            Exit Function
        End If
        ValidateIntegerAndZero = True
    End Function

    ''' <summary>
    ''' 验证数字格式 
    ''' create:YangSJ
    ''' </summary>
    ''' <param name="txtInteger">文本控件</param>
    ''' <param name="isInquiry">是否必填</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Shared Function ValidateInteger(ByVal txtInteger As Camstar.WebClient.FormsBuilder.WebControls.TextBox, ByVal intMax As Integer, ByVal strMax As String, ByVal isInquiry As Boolean, ByRef strMessage As String) As Boolean
        Dim strInteger As String = txtInteger.TextControl.Text
        Dim intStr As Integer = 0
        ValidateInteger = False
        If String.IsNullOrWhiteSpace(strInteger) Then
            If isInquiry Then
                strMessage = String.Format("请输入{0}", txtInteger.Text)
            Else
                ValidateInteger = True
            End If
            Exit Function
        End If

        If Not Integer.TryParse(strInteger, intStr) Then
            strMessage = String.Format("{0}应为数字", txtInteger.Text)
            Exit Function
        End If

        If intStr < 1 Then
            strMessage = String.Format("{0}应大于零", txtInteger.Text)
            Exit Function
        End If

        If intStr > intMax Then
            strMessage = String.Format("{0}应小于{1}", txtInteger.Text, intMax)
            Exit Function
        End If
        ValidateInteger = True
    End Function

    ''' <summary>
    ''' 开始，完成日期格式验证 
    ''' create:YangSJ
    ''' </summary>
    ''' <param name="txtStart">开始文本</param>
    ''' <param name="txtCompletion">完成文本</param>
    ''' <param name="strStartDate">开始值</param>
    ''' <param name="strCompletionDate">完成值</param>
    ''' <param name="strMessage"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Shared Function VlidateDateFormat(ByVal txtStart As String, ByVal txtCompletion As String, ByVal strStartDate As String, ByVal strCompletionDate As String, ByRef strMessage As String) As Boolean
        Dim dateStartDate As DateTime
        Dim dateCompletionDate As DateTime
        VlidateDateFormat = False
        If String.IsNullOrWhiteSpace(strStartDate) Then
            strMessage = String.Format("请输入{0}", txtStart)
            Exit Function
        End If

        If Not DateTime.TryParse(strStartDate, dateStartDate) Then
            strMessage = String.Format("{0}格式错误", txtStart)
            Exit Function
        End If

        If String.IsNullOrWhiteSpace(strCompletionDate) Then
            strMessage = String.Format("请输入{0}", txtCompletion)
            Exit Function
        End If

        If Not DateTime.TryParse(strCompletionDate, dateCompletionDate) Then
            strMessage = String.Format("{0}格式错误", txtCompletion)
            Exit Function
        End If

        If dateCompletionDate < dateStartDate Then
            strMessage = String.Format("{0}需小于{1}", txtStart, txtCompletion)
            Exit Function
        End If
        VlidateDateFormat = True
    End Function

    ''' <summary>
    ''' 日期格式验证 
    ''' create:YangSJ
    ''' </summary>
    ''' <param name="strDate"></param>
    ''' <param name="strMessage"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Shared Function VlidateDateFormat(ByVal txtDate As String, ByVal strDate As String, ByRef strMessage As String) As Boolean
        Dim dateStartDate As DateTime
        VlidateDateFormat = False
        If String.IsNullOrWhiteSpace(strDate) Then
            strMessage = String.Format("请输入{0}", txtDate)
            Exit Function
        End If

        If Not DateTime.TryParse(strDate, dateStartDate) Then
            strMessage = String.Format("{0}格式错误", txtDate)
            Exit Function
        End If
        VlidateDateFormat = True
    End Function

    ''' <summary>
    ''' 设置表格批量选择方式  
    ''' create:YangSJ
    ''' </summary>
    ''' <param name="intType">0全选，1反选，2全不选</param>
    ''' <remarks></remarks>
    Shared Sub ResetGridCheckStatus(ByVal wgGrid As UltraWebGrid, ByVal strCheckKeyName As String, ByVal intType As Integer)


        For i As Integer = 0 To wgGrid.Rows.Count - 1
            Dim ckSelect As UltraGridCell = wgGrid.Rows(i).Cells.FromKey(strCheckKeyName)

            If ckSelect.Column.AllowUpdate = 0 Then
                Continue For
            End If
            If ckSelect.Column.Hidden Then
                Continue For
            End If

            If ckSelect.AllowEditing = AllowEditing.No Then 'add:Wangjh
                Continue For
            End If

            If intType = 0 Then
                ckSelect.Value = True
                If ckSelect.Row.HasChildRows Then '选择子表的行 add:Wangjh 20171024
                    For Each childRow As UltraGridRow In ckSelect.Row.Rows
                        Dim childCkSelect As UltraGridCell = childRow.Cells.FromKey(strCheckKeyName) 'strCheckKeyName
                        If childCkSelect Is Nothing Then
                            Continue For
                        End If
                        If childCkSelect.Column.AllowUpdate = 0 Then
                            Continue For
                        End If
                        If childCkSelect.Column.Hidden Then
                            Continue For
                        End If
                        childCkSelect.Value = True

                    Next
                End If
            ElseIf intType = 1 Then
                ckSelect.Value = Not Boolean.Parse(ckSelect.Value)
                If ckSelect.Row.HasChildRows Then '选择子表的行 add:Wangjh 20171024
                    For Each childRow As UltraGridRow In ckSelect.Row.Rows
                        Dim childCkSelect As UltraGridCell = childRow.Cells.FromKey(strCheckKeyName) 'strCheckKeyName
                        If childCkSelect Is Nothing Then
                            Continue For
                        End If
                        If childCkSelect.Column.AllowUpdate = 0 Then
                            Continue For
                        End If
                        If childCkSelect.Column.Hidden Then
                            Continue For
                        End If
                        childCkSelect.Value = Not childCkSelect.Value
                    Next
                End If
            ElseIf intType = 2 Then
                ckSelect.Value = False
                If ckSelect.Row.HasChildRows Then '选择子表的行 add:Wangjh 20171024
                    For Each childRow As UltraGridRow In ckSelect.Row.Rows
                        Dim childCkSelect As UltraGridCell = childRow.Cells.FromKey(strCheckKeyName) 'strCheckKeyName
                        If childCkSelect Is Nothing Then
                            Continue For
                        End If
                        If childCkSelect.Column.AllowUpdate = 0 Then
                            Continue For
                        End If
                        If childCkSelect.Column.Hidden Then
                            Continue For
                        End If
                        childCkSelect.Value = False
                    Next
                End If
            End If

        Next
    End Sub

    ''' <summary>
    ''' 初始化流水卡数据表格
    ''' create:YangSJ
    ''' </summary>
    ''' <remarks></remarks>
    Shared Sub IniResultGrid(ByVal wg As UltraWebGrid, ByVal GridType As GridType)
        If GridType = GridType.Issue Then
            wg.DisplayLayout.CellClickActionDefault = CellClickAction.RowSelect
        Else
            wg.DisplayLayout.CellClickActionDefault = CellClickAction.CellSelect
        End If

        Dim sumContainer As UltraGridBand = wg.Bands.FromKey("sumContainer")

        Dim col = New UltraGridColumn("ckSelect", "选择", ColumnType.CheckBox, Nothing)
        col.Width = 30
        col.AllowUpdate = AllowUpdate.Yes
        If GridType = GridType.Issue Then
            col.Hidden = True
        End If
        sumContainer.Columns.Insert(0, col)


        sumContainer.Columns.Add(NewGridRow("TogatherFlag", "", "TOGETHERFLAG", Nothing, 0, True))
        If GridType = uLMS_CommonFunction.GridType.WorkReport Then
            sumContainer.Columns.Add(NewGridRow("ProductName", "零件号", "PRODUCTNAME", Nothing, 100, True))
            sumContainer.Columns.Add(NewGridRow("ContainerName", "批次卡", "CONTAINERNAME", Nothing, 130, True))
            ' sumContainer.Columns.Add(NewGridRow("ContainerNameInfo", "件号/批次号", "CONTAINERNAMEINFO", Nothing, 130, False)) 'update:Wangjh 20180801 零件号->件号
        Else
            sumContainer.Columns.Add(NewGridRow("ProductName", "零件号", "PRODUCTNAME", Nothing, 100, True))
            sumContainer.Columns.Add(NewGridRow("ContainerName", "批次卡", "CONTAINERNAME", Nothing, 0, True))
        End If
        sumContainer.Columns.Add(NewGridRow("ProductBatch", "件号/批次号", "ProductBatch", Nothing, 130, False)) 'add：Wangjh 20180801
        sumContainer.Columns.Add(NewGridRow("WORKFLOWNAMEVERSION", "工艺规程及版本", "WORKFLOWNAMEVERSION", Nothing, 130, False)) 'add：longb 20221026
        If GridType <> uLMS_CommonFunction.GridType.FinishegCheck_ReWork_Print Then
            sumContainer.Columns.Add(NewGridRow("TogatherFlagName", "批次号", "TOGETHERFLAGNAME", Nothing, 70, True))
            ' If GridType <> uLMS_CommonFunction.GridType.WorkReport Then
            'sumContainer.Columns.FromKey("TogatherFlagName").Hidden = True
            'End If
        End If
        If GridType = GridType.FinishegCheck_ReWork_Print Or GridType = GridType.FactoryShip Then
            sumContainer.Columns.Add(NewGridRow("ProductDescription", "零件描述", "PRODUCTDESCRIPTION", Nothing, 100, False))
        Else
            sumContainer.Columns.Add(NewGridRow("ProductDescription", "零件描述", "PRODUCTDESCRIPTION", Nothing, 0, True))
        End If
        sumContainer.Columns.Add(NewGridRow("ProductRev", "零件版本", "PRODUCTREVISION", Nothing, 0, True))
        If GridType = uLMS_CommonFunction.GridType.WorkReport Or GridType = GridType.FinishegCheck_ReWork_Print Then
            sumContainer.Columns.Add(NewGridRow("PlanQty", "计划数", "PLANQTY", Nothing, 50, True))
        Else
            sumContainer.Columns.Add(NewGridRow("PlanQty", "计划数", "PLANQTY", Nothing, 50, False))
        End If

        sumContainer.Columns.Add(NewGridRow("WipTotalQty", "在制总数", "WIPQTY", Nothing, 60, False))
        sumContainer.Columns.Add(NewGridRow("WipQty", "", "WIPQTY", Nothing, 0, True))
        If GridType <> GridType.FinishegCheck_ReWork_Print And GridType <> GridType.WorkReport Then
            sumContainer.Columns.Add(NewGridRow("WorkflowStepName", "当前工序", "WORKFLOWSTEPNAME", Nothing, 180, False))
        Else
            sumContainer.Columns.Add(NewGridRow("WorkflowStepName", "工序", "WORKFLOWSTEPNAME", Nothing, 180, False))
        End If
        If GridType = GridType.WorkReport Then
            sumContainer.Columns.Add(NewGridRow("NowWorkflowStepName", "当前工序", "NOWWORKFLOWSTEPNAME", Nothing, 120, False))
        End If
        sumContainer.Columns.Add(NewGridRow("ContainerTypeName", "批次卡类型", "CONTAINERTYPENAME", Nothing, 80, False))

        If GridType <> uLMS_CommonFunction.GridType.WorkReport And GridType <> GridType.FinishegCheck_ReWork_Print And GridType <> GridType.FactoryShip Then
            If GridType = uLMS_CommonFunction.GridType.Preparation Then 'add YangJiang 20180515
                sumContainer.Columns.Add(NewGridRow("DispartDate", "派工时间", "DispartDate", "yyyy-MM-dd", 70, False))
                sumContainer.Columns.Add(NewGridRow("DispartFinishDate", "要求完成时间", "DispartFinishDate", "yyyy-MM-dd", 90, False))
            Else
                sumContainer.Columns.Add(NewGridRow("PlannedStartDate", "计划开始", "PLANNEDSTARTDATE", "yyyy-MM-dd", 70, False))
                sumContainer.Columns.Add(NewGridRow("PlannedCompletionDate", "计划完成", "PLANNEDCOMPLETIONDATE", "yyyy-MM-dd", 70, False))
            End If

        End If
        If GridType = uLMS_CommonFunction.GridType.TeamDispatch Then 'Add:Wangjh 2017-7-12 
            sumContainer.Columns.Add(NewGridRow("TeamName", "班组", "TeamName", Nothing, 100, False))
        End If
        If GridType = uLMS_CommonFunction.GridType.Preparation Then 'Add:Wangjh 2017-9-11
            sumContainer.Columns.Add(NewGridRow("TeamID", String.Empty, "TEAMID", Nothing, 0, True))
        End If

        sumContainer.Columns.Add(NewGridRow("ContainerType", String.Empty, "CONTAINERTYPE", Nothing, 0, True))
        sumContainer.Columns.Add(NewGridRow("IsHold", "暂停", "IsHold", Nothing, 0, True)) 'add by tianFW 2018年8月23日
        If GridType = GridType.StepCheck Then
            sumContainer.Columns.Add(NewGridRow("IsKey", "关键序", "ISKEY", Nothing, 50, False))
            sumContainer.Columns.Add(NewGridRow("FirstCheckNum", "首检", "FIRSTCHECKNUM", Nothing, 40, False))
            sumContainer.Columns.Add(NewGridRow("StepCheckNum", "工序检", "STEPCHECKNUM", Nothing, 50, False))
            sumContainer.Columns.Add(NewGridRow("SpecName", "", "SPECNAME", Nothing, 0, True))
            sumContainer.Columns.Add(NewGridRow("SpecRevision", "", "SPECREVISION", Nothing, 0, True))
            sumContainer.Columns.Add(NewGridRow("ParentSpecNO", "", "PARENTSPECNO", Nothing, 0, True))
            sumContainer.Columns.Add(NewGridRow("NonConformingNum", "", "NONCONFORMINGNUM", Nothing, 0, True))
            sumContainer.Columns.Add(NewGridRow("AllLossQty", "报废数", "ALLLOSSQTY", Nothing, 50, True))
            sumContainer.Columns.Add(NewGridRow("OriginalFactoryID", "批次分厂", "ORIGINALFACTORYID", Nothing, 0, True))
            sumContainer.Columns.Add(NewGridRow("ZBJH", "组别件号", "ZBJH", Nothing, 0, True))
        ElseIf GridType = GridType.WorkReport Then
            sumContainer.Columns.Add(NewGridRow("FirstCheckNum", "首检", "FIRSTCHECKNUM", Nothing, 40, True))
            sumContainer.Columns.Add(NewGridRow("StepCheckNum", "工序检", "STEPCHECKNUM", Nothing, 50, True))
            sumContainer.Columns.Add(NewGridRow("AllLossQty", "报废数", "ALLLOSSQTY", Nothing, 50, True))
            sumContainer.Columns.Add(NewGridRow("PlannedStartDate", "计划开始", "PLANNEDSTARTDATE", "yyyy-MM-dd", 0, True))
            sumContainer.Columns.Add(NewGridRow("PlannedFinishDate", "计划完成", "PLANNEDFINISHDATE", "yyyy-MM-dd", 0, True))
        ElseIf GridType = GridType.Commissioning Then
            sumContainer.Columns.Add(NewGridRow("CommissioningNum", "外委", "COMMISSIONINGNUM", Nothing, 0, True))
            sumContainer.Columns.Add(NewGridRow("ISCommissioning", "当前序外委", "ISCOMMISSIONING", Nothing, 0, True))
            sumContainer.Columns.Add(NewGridRow("OriginalFactoryID", "批次分厂", "ORIGINALFACTORYID", Nothing, 0, True))
            sumContainer.Columns.Add(NewGridRow("FactoryID", "批次当前分厂", "FACTORYID", Nothing, 0, True))
        End If

        If GridType = GridType.StepDispatch Then 'add tianFW 2017/09/27
            sumContainer.Columns.Add(NewGridRow("AllLossQty", "报废数", "ALLLOSSQTY", Nothing, 0, True))
        End If
        sumContainer.Columns.Add(NewGridRow("SpecNO", "工序号", "SpecNo", Nothing, 0, True))

        sumContainer.Columns.Add(NewGridRow("WorkCenterName", "工区", "WORKCENTERNAME", Nothing, 0, True))
        sumContainer.Columns.Add(NewGridRow("WorkCenterID", String.Empty, "WORKCENTERID", Nothing, 0, True))
        If GridType = GridType.WorkReport Then
            sumContainer.Columns.Add(NewGridRow("WorkReportNum", "已报总数", "WORKREPORTNUM", Nothing, 60, False))
            sumContainer.Columns.Add(NewGridRow("PriorityCode", "优先级", "PRIORITYCODE", Nothing, 45, False))
        Else
            sumContainer.Columns.Add(NewGridRow("WorkReportNum", "报工数", "WORKREPORTNUM", Nothing, 0, True))
        End If
        sumContainer.Columns.Add(NewGridRow("ProductID", String.Empty, "PRODUCTID", Nothing, 0, True))
        sumContainer.Columns.Add(NewGridRow("WorkflowStepID", String.Empty, "WORKFLOWSTEPID", Nothing, 0, True))
        sumContainer.Columns.Add(NewGridRow("WorkflowID", String.Empty, "WORKFLOWID", Nothing, 0, True))
        sumContainer.Columns.Add(NewGridRow("Sequence", String.Empty, "SEQUENCE", Nothing, 0, True))
        sumContainer.Columns.Add(NewGridRow("ContainerID", String.Empty, "CONTAINERID", Nothing, 0, True))
        sumContainer.Columns.Add(NewGridRow("BomID", String.Empty, "BOMID", Nothing, 0, True))
        sumContainer.Columns.Add(NewGridRow("ContainerTeamDispatchID", String.Empty, "TEAMDISPATCHID", Nothing, 0, True))
        sumContainer.Columns.Add(NewGridRow("ContainerStepDispatchID", String.Empty, "CONTAINERSTEPDISPATCHID", Nothing, 0, True))
        sumContainer.Columns.Add(NewGridRow("ContainerShipRecordID", String.Empty, "SHIPID", Nothing, 0, True))
        sumContainer.Columns.Add(NewGridRow("ResourceID", String.Empty, "RESOURCEID", Nothing, 0, True))
        If GridType = GridType.ContainerPrint Then 'add:Wangjh 2017-8-11
            sumContainer.Columns.Add(NewGridRow("Isselfmfg", "是否自投", "Isselfmfg", Nothing, 120, True))
            sumContainer.Columns.Insert(2, NewGridRow("PdfPrint", "打印流水卡", String.Empty, Nothing, 120, False))
        End If
        If GridType = GridType.StepDispatch Or GridType = GridType.WorkReport Or GridType = GridType.StepCheck Then 'add:Wangjh 20171128 增加超越单
            sumContainer.Columns.Add(NewGridRow("IsHaveSurpass", "超越单", "IsHaveSurpass", Nothing, 50, False))
        End If

        If GridType = GridType.FactoryShip Then 'add:Wangjh 20180314
            sumContainer.Columns.Add(NewGridRow("SplitFromID", "超越单", "SplitFromID", Nothing, 0, True))
        End If

        If GridType = GridType.WorkCenterDispatch Then
            sumContainer.Columns.Add(NewGridRow("ShipID", "ShipID", "ShipID", Nothing, 0, True))
            sumContainer.Columns.Add(NewGridRow("OriginalFactoryID", "originalfactoryid", "originalfactoryid", Nothing, 0, True))
        End If

        Dim sonContainer As UltraGridBand = wg.Bands.FromKey("sonContainer")

        col = New UltraGridColumn("ckSelect", "选择", ColumnType.CheckBox, Nothing)
        col.Width = 30
        col.AllowUpdate = AllowUpdate.Yes

        If GridType = GridType.Issue Then
            col.Hidden = True
        End If
        sonContainer.Columns.Insert(0, col)

        sonContainer.Columns.Add(NewGridRow("ContainerName", "批次卡号", "CONTAINERNAME", Nothing, 200, False))
        If GridType <> GridType.FinishegCheck_ReWork_Print And GridType <> GridType.StepCheck Then
            sonContainer.Columns.Add(NewGridRow("TeamName", "班组", "TEAMNAME", Nothing, 100, False))
        End If
        sonContainer.Columns.Add(NewGridRow("WorkCenterName", "工区", "WORKCENTERNAME", Nothing, 0, True))
        sonContainer.Columns.Add(NewGridRow("WipQty", "在制数", "QTY", Nothing, 50, False))
        If GridType = GridType.StepCheck Then
            sonContainer.Columns.Add(NewGridRow("IsKey", "关键序", "ISKEY", Nothing, 50, False))
            sonContainer.Columns.Add(NewGridRow("FirstCheckNum", "首检", "FIRSTCHECKNUM", Nothing, 40, False))
            sonContainer.Columns.Add(NewGridRow("StepCheckNum", "工序检", "STEPCHECKNUM", Nothing, 50, False))
            sonContainer.Columns.Add(NewGridRow("SpecName", "", "SPECNAME", Nothing, 0, True))
            sonContainer.Columns.Add(NewGridRow("SpecRevision", "", "SPECREVISION", Nothing, 0, True))
            sonContainer.Columns.Add(NewGridRow("ParentSpecNO", "", "PARENTSPECNO", Nothing, 0, True))
            sonContainer.Columns.Add(NewGridRow("NonConformingNum", "", "NONCONFORMINGNUM", Nothing, 0, True))
            sonContainer.Columns.Add(NewGridRow("AllLossQty", "报废数", "ALLLOSSQTY", Nothing, 50, True))
            sonContainer.Columns.Add(NewGridRow("OriginalFactoryID", "批次分厂", "ORIGINALFACTORYID", Nothing, 0, True))
        ElseIf GridType = GridType.WorkReport Then
            sonContainer.Columns.Add(NewGridRow("FirstCheckNum", "首检", "FIRSTCHECKNUM", Nothing, 40, True))
            sonContainer.Columns.Add(NewGridRow("StepCheckNum", "工序检", "STEPCHECKNUM", Nothing, 50, True))
            sonContainer.Columns.Add(NewGridRow("NowWorkflowStepName", "当前工序", "NOWWORKFLOWSTEPNAME", Nothing, 0, True))
            sonContainer.Columns.Add(NewGridRow("AllLossQty", "报废数", "ALLLOSSQTY", Nothing, 50, True))
            sonContainer.Columns.Add(NewGridRow("PriorityCode", "优先级", "PRIORITYCODE", Nothing, 45, False))
            sonContainer.Columns.Add(NewGridRow("PlannedStartDate", "计划开始", "PLANNEDSTARTDATE", "yyyy-MM-dd", 0, True))
            sonContainer.Columns.Add(NewGridRow("PlannedFinishDate", "计划完成", "PLANNEDFINISHDATE", "yyyy-MM-dd", 0, True))
        ElseIf GridType = GridType.Commissioning Then
            sonContainer.Columns.Add(NewGridRow("CommissioningNum", "外委", "COMMISSIONINGNUM", Nothing, 0, True))
            sonContainer.Columns.Add(NewGridRow("ISCommissioning", "当前序外委", "ISCOMMISSIONING", Nothing, 0, True))
            sonContainer.Columns.Add(NewGridRow("OriginalFactoryID", "批次分厂", "ORIGINALFACTORYID", Nothing, 0, True))
            sonContainer.Columns.Add(NewGridRow("FactoryID", "批次当前分厂", "FACTORYID", Nothing, 0, True))
        ElseIf GridType = GridType.ContainerPrint Then 'add:Wangjh 2017-8-11
            sonContainer.Columns.Add(NewGridRow("Isselfmfg", "是否自投", "Isselfmfg", Nothing, 120, True))
            sonContainer.Columns.Insert(2, NewGridRow("PdfPrint", "打印流水卡", String.Empty, Nothing, 120, False))
        End If
        sonContainer.Columns.Add(NewGridRow("WorkReportNum", "报工数", "WORKREPORTNUM", Nothing, 0, True))
        sonContainer.Columns.Add(NewGridRow("TeamID", String.Empty, "TEAMID", Nothing, 0, True))
        sonContainer.Columns.Add(NewGridRow("ContainerID", String.Empty, "CONTAINERID", Nothing, 0, True))
        sonContainer.Columns.Add(NewGridRow("BomID", String.Empty, "BOMID", Nothing, 0, True))
        sonContainer.Columns.Add(NewGridRow("ContainerTeamDispatchID", String.Empty, "TEAMDISPATCHID", Nothing, 0, True))
        sonContainer.Columns.Add(NewGridRow("ContainerStepDispatchID", String.Empty, "CONTAINERSTEPDISPATCHID", Nothing, 0, True))
        sonContainer.Columns.Add(NewGridRow("ContainerShipRecordID", String.Empty, "SHIPID", Nothing, 0, True))
        sonContainer.Columns.Add(NewGridRow("ResourceID", String.Empty, "RESOURCEID", Nothing, 0, True))
        sonContainer.Columns.Add(NewGridRow("IsHold", "暂停", "IsHold", Nothing, 0, True)) 'add by tianFW 2018年8月23日
        If GridType = GridType.StepDispatch Then 'add tianFW 2017/09/27
            sonContainer.Columns.Add(NewGridRow("AllLossQty", "报废数", "ALLLOSSQTY", Nothing, 0, True))
        End If
        If GridType = GridType.StepDispatch Or GridType = GridType.WorkReport Or GridType = GridType.StepCheck Then 'add:Wangjh 20171128 增加超越单
            sonContainer.Columns.Add(NewGridRow("IsHaveSurpass", "超越单", "IsHaveSurpass", Nothing, 50, False))
        End If
        If GridType = GridType.FactoryShip Then 'add:Wangjh 20180314
            sonContainer.Columns.Add(NewGridRow("SplitFromID", "超越单", "SplitFromID", Nothing, 0, True))
        End If
        If GridType = GridType.WorkCenterDispatch Then
            sonContainer.Columns.Add(NewGridRow("ShipID", "ShipID", "ShipID", Nothing, 0, True))
        End If
        If GridType = uLMS_CommonFunction.GridType.Preparation Then 'add YangJiang 20180515
            sonContainer.Columns.Add(NewGridRow("DispartDate", "派工时间", "DispartDate", "yyyy-MM-dd", 70, False))
            sonContainer.Columns.Add(NewGridRow("DispartFinishDate", "要求完成时间", "DispartFinishDate", "yyyy-MM-dd", 90, False))
        End If
    End Sub

    ''' <summary>
    ''' 初始化表格列
    ''' </summary>
    ''' <param name="key"></param>
    ''' <param name="headerText"></param>
    ''' <param name="colType"></param>
    ''' <param name="baseColumnName"></param>
    ''' <param name="colFormat"></param>
    ''' <param name="colWidth"></param>
    ''' <param name="isHidden"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function NewGridRow(ByVal key As String, ByVal headerText As String, ByVal baseColumnName As String, ByVal colFormat As String, ByVal colWidth As Integer, ByVal isHidden As Boolean) As UltraGridColumn
        Dim col As UltraGridColumn = New UltraGridColumn(key, headerText, ColumnType.NotSet, Nothing)
        If baseColumnName IsNot Nothing Then
            col.BaseColumnName = baseColumnName
        End If
        If isHidden Then
            col.Hidden = isHidden
        End If
        col.Width = colWidth
        If colFormat IsNot Nothing Then
            col.Format = colFormat
        End If
        NewGridRow = col
    End Function

    ''' <summary>
    ''' 单选行及选择父行控制行选择
    ''' create:YangSJ
    ''' </summary>
    ''' <param name="checkRow"></param>
    ''' <remarks></remarks>
    Shared Sub CheckSumContainerRow(ByVal wg As UltraWebGrid, ByVal checkRow As UltraGridRow)
        If checkRow.Band.Columns.FromKey("ckSelect").Hidden Then
            Exit Sub
        End If
        Dim val As Boolean = checkRow.Cells.FromKey("ckSelect").Value
        Dim index As Integer = checkRow.Index
        If checkRow.ParentRow IsNot Nothing Then
            If val Then
                checkRow.ParentRow.Cells.FromKey("ckSelect").Value = val
            End If
            index = checkRow.ParentRow.Index
        End If
        '控制表格单选
        For Each row As UltraGridRow In wg.Rows
            If row.Cells.FromKey("ckSelect").Value = False Then
                Continue For
            End If
            If row.Index = index Then
                Continue For
            End If
            row.Cells.FromKey("ckSelect").Value = False
            For Each _row As UltraGridRow In row.Rows
                _row.Cells.FromKey("ckSelect").Value = False
            Next
        Next
        If checkRow.Rows.Count = 0 Then
            Exit Sub
        End If
        '  Dim strType As String = checkRow.Cells.FromKey("ContainerType").Value
        If checkRow.ParentRow Is Nothing Then
            For Each row As UltraGridRow In checkRow.Rows
                row.Cells.FromKey("ckSelect").Value = val
            Next
        End If


    End Sub

    ''' <summary>
    ''' 派工、外委、工区协助等工序排除 create TianFW
    ''' </summary>
    ''' <param name="wg"></param>
    ''' <remarks></remarks>
    Shared Sub ClearNoUseWorkflowStepID(ByVal wg As UltraWebGrid, ByVal dt_commission As DataTable, ByVal dt_ship As DataTable, ByVal dt_workCenter As DataTable, ByVal dt_ControlCodeAndLastCheck As DataTable, ByVal dt_Dispatched As DataTable, ByVal key As String)
        For Each ur As UltraGridRow In wg.Rows

            If key <> "Dispatch" Then
                If dt_Dispatched.Rows.Count > 0 Then '已派工工序表
                    For Each row As DataRow In dt_Dispatched.Rows
                        If row("WORKFLOWSTEPID").ToString = ur.Cells.FromKey("WorkFlowStepID").Value Then
                            ur.Hidden = True
                            Exit For
                        End If
                    Next
                End If
                If ur.Hidden = True Then
                    Continue For
                End If
            End If

            If key <> "Commission" Then
                If dt_commission.Rows.Count > 0 Then '已经外委的工序表
                    'Dim firstsequence As Integer = Integer.Parse(dt_commission.Rows(0)("FIRSTSEQUENCE"))
                    'Dim lastsequence As Integer = Integer.Parse(dt_commission.Rows(0)("LASTSEQUENCE"))
                    Dim ishide = False
                    For Each dtr As DataRow In dt_commission.Rows
                        If Convert.ToInt32(ur.Cells.FromKey("Sequence").Value) >= dtr("FIRSTSEQUENCE") And Convert.ToInt32(ur.Cells.FromKey("Sequence").Value) < dtr("LASTSEQUENCE") Then
                            If dtr("WORKFLOWSTEPID").ToString = ur.Cells.FromKey("WorkFlowStepID").Value Or ishide Then
                                ishide = True
                                ur.Hidden = True
                                Continue For
                            End If
                        End If
                    Next
                End If
            End If

            If key <> "Ship" Then
                If dt_ship.Rows.Count > 0 Then '临时转工的工序表
                    For Each row As DataRow In dt_ship.Rows
                        If row("WORKFLOWSTEPID").ToString = ur.Cells.FromKey("WorkFlowStepID").Value Then
                            ur.Hidden = True
                            Exit For
                        End If
                    Next
                    If ur.Hidden = True Then
                        Continue For
                    End If
                End If
            End If

            If key <> "workCenter" Then
                If dt_workCenter.Rows.Count > 0 Then '工区协作工序表
                    For Each row As DataRow In dt_workCenter.Rows
                        If row("WORKFLOWSTEPID").ToString = ur.Cells.FromKey("WorkFlowStepID").Value Then
                            ur.Hidden = True
                            Exit For
                        End If
                    Next
                    If ur.Hidden = True Then
                        Continue For
                    End If
                End If
            End If

            If dt_ControlCodeAndLastCheck.Rows.Count > 0 Then '固定外委和检验序工序表
                For Each row As DataRow In dt_ControlCodeAndLastCheck.Rows
                    If row("WORKFLOWSTEPID").ToString = ur.Cells.FromKey("WorkFlowStepID").Value Then
                        ur.Hidden = True
                        Exit For
                    End If
                Next
                If ur.Hidden = True Then
                    Continue For
                End If
            End If
        Next
    End Sub

    ''' <summary>
    ''' 获取自然数表查询Sql语句
    ''' </summary>
    ''' <param name="starNatural"></param>
    ''' <param name="endNatural"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Shared Function GetNaturalNumberSql(ByVal starNatural As Integer, ByVal endNatural As Integer) As String
        Dim strsql As String = ""
        For i As Integer = starNatural To endNatural
            If i < endNatural Then
                strsql += "SELECT " + i.ToString + " PRIORITYCODE FROM DUAL UNION "
            Else
                strsql += "SELECT " + i.ToString + " PRIORITYCODE FROM DUAL "
            End If
        Next
        Return strsql
    End Function

    ''' <summary>
    ''' 获取流水卡列表选择数据
    ''' create:YangSJ
    ''' </summary>
    ''' <param name="wg"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Shared Function GetChooseContainerInfo(ByVal wg As UltraWebGrid) As DataTable
        Dim dt As New DataTable
        For Each col As UltraGridColumn In wg.Columns
            If Not dt.Columns.Contains(col.Key) Then
                dt.Columns.Add(col.Key)
            End If
        Next

        Dim dr As DataRow
        For Each row As UltraGridRow In wg.Rows
            If row.Cells.FromKey("ckSelect").Value = False Then
                Continue For
            End If
            If String.IsNullOrWhiteSpace(row.Cells.FromKey("ContainerID").Text) Then
                For Each _row As UltraGridRow In row.Rows
                    If _row.Cells.FromKey("ckSelect").Value = False Then
                        Continue For
                    End If
                    dr = dt.NewRow '获取批量单件加工流水卡
                    For Each col As UltraGridColumn In wg.Columns

                        If _row.Band.Columns.FromKey(col.Key) IsNot Nothing Then
                            dr(col.Key) = _row.Cells.FromKey(col.Key).Value
                        Else
                            dr(col.Key) = row.Cells.FromKey(col.Key).Value
                        End If
                    Next
                    dt.Rows.Add(dr)
                Next
            Else
                dr = dt.NewRow '获取非单件加工流水卡
                For Each col As UltraGridColumn In wg.Columns
                    dr(col.Key) = row.Cells.FromKey(col.Key).Value
                Next
                dt.Rows.Add(dr)
            End If
        Next
        dt.AcceptChanges()
        GetChooseContainerInfo = dt
    End Function

    ''' <summary>
    ''' 获取流水卡列表选择数据,并获取其索引
    ''' create:Wangjh
    ''' </summary>
    ''' <param name="wg"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Shared Function GetChooseContainerInfo(ByVal wg As UltraWebGrid, ByRef indexPara As Dictionary(Of Integer, List(Of Integer))) As DataTable
        Dim dt As New DataTable
        For Each col As UltraGridColumn In wg.Columns
            dt.Columns.Add(col.Key)
        Next

        Dim dr As DataRow
        For Each row As UltraGridRow In wg.Rows
            If row.Cells.FromKey("ckSelect").Value = False Then
                Continue For
            End If
            indexPara.Add(row.Index, Nothing)
            If String.IsNullOrWhiteSpace(row.Cells.FromKey("ContainerID").Text) Then
                Dim sonIndex As List(Of Integer) = New List(Of Integer)
                For Each _row As UltraGridRow In row.Rows
                    If _row.Cells.FromKey("ckSelect").Value = False Then
                        Continue For
                    End If
                    sonIndex.Add(_row.Index)
                    dr = dt.NewRow '获取批量单件加工流水卡
                    For Each col As UltraGridColumn In wg.Columns

                        If _row.Band.Columns.FromKey(col.Key) IsNot Nothing Then
                            dr(col.Key) = _row.Cells.FromKey(col.Key).Value
                        Else
                            dr(col.Key) = row.Cells.FromKey(col.Key).Value
                        End If
                    Next
                    dt.Rows.Add(dr)
                Next
                indexPara(row.Index) = sonIndex
            Else
                dr = dt.NewRow '获取非单件加工流水卡
                For Each col As UltraGridColumn In wg.Columns
                    dr(col.Key) = row.Cells.FromKey(col.Key).Value
                Next
                dt.Rows.Add(dr)
            End If
        Next
        dt.AcceptChanges()
        GetChooseContainerInfo = dt
    End Function

    ''' <summary>
    ''' 根据索引删除表格的行
    ''' create:Wangjh
    ''' </summary>
    ''' <param name="wg"></param>
    ''' <param name="indexPara"></param>
    ''' <remarks></remarks>
    Shared Sub DeleteGridRowByIndex(ByVal wg As UltraWebGrid, ByVal indexPara As Dictionary(Of Integer, List(Of Integer)))
        Dim m As Integer = 0 '记录父级删除的个数
        For Each value As Integer In indexPara.Keys
            Dim faIndex = value - m
            If indexPara(value) Is Nothing Then '非父子级
                wg.Rows(faIndex).Delete()
            Else '父子级
                If wg.Rows(faIndex).Rows.Count = indexPara(faIndex).Count Then '全选
                    wg.Rows(faIndex).Delete()
                Else '没全选子级
                    Dim n As Integer = 0 '记录子级删除的个数
                    For Each sonIndex As Integer In indexPara(faIndex)
                        sonIndex = sonIndex - n
                        wg.Rows(faIndex).Rows(sonIndex).Delete()
                        n += 1
                    Next
                End If
            End If
            m += 1
        Next
    End Sub

    ''' <summary>
    ''' 表格类型
    ''' </summary>
    ''' <remarks></remarks>
    Enum GridType
        WorkCenterDispatch = 1
        TeamDispatch = 2
        StepDispatch = 3
        StepCheck = 4
        Preparation = 5
        Issue = 6
        WorkReport = 7
        FactoryShip = 8
        Commissioning = 9
        ContainerPrint = 10 'add:Wangjh 2017-7-19 关键过程记录打印
        FinishegCheck_ReWork_Print = 11 'add tianFW 2017.08.23 成检、返工返修打印
        ContainerNoChange = 12 'add tianfw 2017.08 批次变号 
    End Enum

    ''' <summary>
    ''' 获取GUID转换成的16位字符串 create by tianFW 2019年1月5日
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function GenerateGuidTo16StringID() As String
        Dim buffer As Byte() = Guid.NewGuid().ToByteArray()
        Dim value As String = Hex(BitConverter.ToInt64(buffer, 0)).ToLower()
        While (value.Length < 16)
            value = "0" & value
        End While
        Return value
    End Function
#End Region

    ''' <summary>
    ''' add by yuxj 20171205
    ''' </summary>
    ''' <param name="wbgGrid"></param>
    ''' <param name="key"></param>
    ''' <param name="headerText"></param>
    ''' <param name="baseColumnName"></param>
    ''' <param name="colFormat"></param>
    ''' <param name="colWidth"></param>
    ''' <param name="isHidden"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function GridAddNewCol(ByVal wbgGrid As UltraWebGrid, ByVal key As String, ByVal headerText As String, ByVal baseColumnName As String, ByVal colFormat As String, ByVal colWidth As Integer, ByVal isHidden As Boolean) As UltraWebGrid
        Dim col As UltraGridColumn = New UltraGridColumn(key, headerText, ColumnType.NotSet, Nothing)
        If baseColumnName IsNot Nothing Then
            col.BaseColumnName = baseColumnName
        End If
        If isHidden Then
            col.Hidden = isHidden
        End If
        col.Width = colWidth
        If colFormat IsNot Nothing Then
            col.Format = colFormat
        End If

        wbgGrid.Columns.Add(col)
        GridAddNewCol = wbgGrid
    End Function

    Public Shared Function GridAddNewCol(ByVal wbgGrid As UltraGridBand, ByVal key As String, ByVal headerText As String, ByVal baseColumnName As String, ByVal colFormat As String, ByVal colWidth As Integer, ByVal isHidden As Boolean) As UltraGridBand
        Dim col As UltraGridColumn = New UltraGridColumn(key, headerText, ColumnType.NotSet, Nothing)
        If baseColumnName IsNot Nothing Then
            col.BaseColumnName = baseColumnName
        End If
        If isHidden Then
            col.Hidden = isHidden
        End If
        col.Width = colWidth
        If colFormat IsNot Nothing Then
            col.Format = colFormat
        End If

        wbgGrid.Columns.Add(col)
        GridAddNewCol = wbgGrid
    End Function

    ''' <summary>
    ''' add by yuxj 20171225增加checkbox列
    ''' </summary>
    ''' <param name="wbgGrid"></param>
    ''' <param name="key"></param>
    ''' <param name="headerText"></param>
    ''' <param name="isHidden"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function GridAddChkBoxCol(ByVal wbgGrid As UltraWebGrid, ByVal key As String, ByVal headerText As String, ByVal isHidden As Boolean) As UltraWebGrid
        Dim col As New UltraGridColumn
        col = New UltraGridColumn(key, headerText, ColumnType.CheckBox, Nothing)
        col.AllowUpdate = AllowUpdate.Yes
        col.Width = 30
        col.DataType = "System.Boolean"
        wbgGrid.Columns.Insert(0, col)
        GridAddChkBoxCol = wbgGrid
    End Function

    ''' <summary>
    ''' 处理下拉列表的title add by tianFW 2018年5月11日
    ''' </summary>
    ''' <param name="ddl"></param>
    ''' <remarks></remarks>
    Public Shared Sub DDLAddAttributesOfTitle(ByVal ddl As Camstar.WebClient.FormsBuilder.WebControls.DropDownList)
        For Each item As ListItem In ddl.DropDownControl.Items
            item.Attributes.Add("title", item.Text)
        Next
    End Sub

    Public Shared Sub DDLDataBind(ByVal ddl As Camstar.WebClient.FormsBuilder.WebControls.DropDownList, ByVal DataSource As DataTable, ByVal DataTextField As String, ByVal DataValueField As String)
        ddl.DropDownControl.DataSource = DataSource
        ddl.DropDownControl.DataTextField = DataTextField
        ddl.DropDownControl.DataValueField = DataValueField
        ddl.DropDownControl.DataBind()
    End Sub

    Public Shared Sub DDLSelectedValue(ByVal ddl As Camstar.WebClient.FormsBuilder.WebControls.DropDownList, ByVal DataValue As String)
        If IsNothing(DataValue) Then
            Exit Sub
        End If
        Dim lItem = ddl.DropDownControl.Items.FindByValue(DataValue)
        If IsNothing(lItem) Then
            Exit Sub
        End If
        lItem.Selected = True
    End Sub

    ''' <summary>
    ''' post请求
    ''' add:Wangjh 20220101
    ''' </summary>
    ''' <param name="jsonRequest"></param>
    ''' <param name="url"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function PostRequest(ByVal jsonRequest As String, ByVal url As String) As String
        Dim encoding As System.Text.Encoding = System.Text.Encoding.GetEncoding("UTF-8")

        Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(url)
        request.Method = "POST"
        request.ContentType = "application/x-www-form-urlencoded" 'text/plain，application/x-www-form-urlencoded

        Dim postData() = encoding.GetBytes(jsonRequest)
        request.ContentLength = postData.Length

        Dim requestStream As System.IO.Stream = request.GetRequestStream()
        requestStream.Write(postData, 0, postData.Length)

        requestStream.Close()

        Dim response As System.Net.HttpWebResponse = request.GetResponse()

        Dim responseSream As StreamReader = New StreamReader(response.GetResponseStream())

        Dim html As String = responseSream.ReadToEnd()

        responseSream.Close()
        response.Close()

        Return html
    End Function


#Region "excel导入导出"

    ''' <summary>
    ''' DataTable导出,有标题,返回字节数
    ''' add:Wangjh 20221012
    ''' </summary>
    ''' <param name="SourceTable"></param>
    ''' <param name="title">标题,有值则第一行为标题</param>
    ''' <param name="colWidth">列宽指定每列的宽度,null：全部自动宽度，键值对中无对应索引列的key:自动宽度</param>
    ''' <param name="pigCol">指定有图片的列</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function DataTableExportToExcel(ByVal SourceTable As DataTable, ByVal title As String,
                                                  Optional ByVal colWidth As Dictionary(Of Integer, Integer) = Nothing, Optional ByVal pigCol As Integer() = Nothing) As Byte()
        If SourceTable.Rows.Count = 0 Then
            Return Nothing
        End If

        'PAGE_MAX_ROWS => 每个Sheet页最多能够显示的行数。Office 2003最多可显示65536行
        Const PAGE_MAX_ROWS As Integer = 65536

        'coloumsCount => Excel列数
        Dim coloumsCount As Integer = SourceTable.Columns.Count

        Dim workbook As HSSFWorkbook = New HSSFWorkbook()
        Dim ms As MemoryStream = New MemoryStream()

        ' "单元格样式设置"

        Dim style As NPOI.SS.UserModel.ICellStyle = workbook.CreateCellStyle()

        '水平对齐居中
        style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center

        '设置字体
        Dim font As NPOI.SS.UserModel.IFont = workbook.CreateFont()
        font.FontName = "微软雅黑"
        style.SetFont(font)

        '设置边框
        style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin
        style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin
        style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin
        style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin


        ' 表头样式设置
        Dim headerCellStyle As NPOI.SS.UserModel.ICellStyle = workbook.CreateCellStyle()

        '居中显示
        headerCellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center

        '设置边框
        headerCellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin
        headerCellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin
        headerCellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin
        headerCellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin

        '设置背景色
        headerCellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.LightGreen.Index
        headerCellStyle.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground

        '加粗
        Dim headerFont As NPOI.SS.UserModel.IFont = workbook.CreateFont()
        headerFont.Boldweight = Short.MaxValue
        headerFont.FontName = "微软雅黑"
        headerCellStyle.SetFont(headerFont)

        ' 标题样式设置
        Dim titleCellStyle As NPOI.SS.UserModel.ICellStyle = workbook.CreateCellStyle()

        '居中显示
        titleCellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center

        '设置边框
        titleCellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin
        titleCellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin
        titleCellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin
        titleCellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin

        '设置背景色
        titleCellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.LightGreen.Index
        titleCellStyle.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground

        '加粗
        Dim titleFont As NPOI.SS.UserModel.IFont = workbook.CreateFont()
        titleFont.Boldweight = Short.MaxValue
        titleFont.FontName = "微软雅黑"

        titleCellStyle.SetFont(titleFont)


        Dim sheetCount As Integer = 1

        '每个sheet页达到最大行数限制时，自动创建新的sheet页
        Dim i As Integer
        For i = 0 To SourceTable.Rows.Count - 1 Step (PAGE_MAX_ROWS - 2)
            Dim sheet As HSSFSheet = CType(workbook.CreateSheet("sheet" + sheetCount.ToString()), HSSFSheet)

            '创建第1行：标题行
            Dim titleRow As HSSFRow = CType(sheet.CreateRow(0), HSSFRow)

            '为正确显示合并居中行的边框，第一行除第一列之外全部插入空值
            Dim j As Integer
            For j = 0 To SourceTable.Columns.Count - 1
                If j = 0 Then
                    titleRow.CreateCell(j).SetCellValue(title)
                Else
                    titleRow.CreateCell(j).SetCellValue("")
                End If
                titleRow.Cells(j).CellStyle = titleCellStyle
            Next


            '合并第一行单元格作为Excel标题
            'CellRangeAddress四个参数为：起始行位置，结束行位置，起始列位置，结束列位置（位置由0开始算）
            sheet.AddMergedRegion(New CellRangeAddress(0, 0, 0, coloumsCount - 1))

            '创建第2行：表头行
            Dim headerRow As HSSFRow = CType(sheet.CreateRow(1), HSSFRow)

            '表头行插值并设置样式 
            Dim column As DataColumn
            For Each column In SourceTable.Columns
                If column.Caption.ToString() <> column.ColumnName.ToString() Then
                    headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption)
                Else
                    headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName)
                End If
                headerRow.Cells(column.Ordinal).CellStyle = headerCellStyle
            Next

            '从第3行开始循环插入实际数据
            Dim rowIndex As Integer = 2

            Dim k As Integer
            For k = 0 To PAGE_MAX_ROWS - 2 - 1
                If (k + i) < SourceTable.Rows.Count Then
                    Dim dataRow As HSSFRow = CType(sheet.CreateRow(rowIndex), HSSFRow)

                    For Each column In SourceTable.Columns
                        dataRow.CreateCell(column.Ordinal).SetCellValue(SourceTable.Rows(i + k)(column).ToString())
                        dataRow.Cells(column.Ordinal).CellStyle = style
                        If pigCol IsNot Nothing Then '是否是图片列
                            If pigCol.Contains(column.Ordinal) And File.Exists(SourceTable.Rows(i + k)(column).ToString()) Then
                                dataRow.Cells(column.Ordinal).SetCellValue("")
                                AddPictureToCell(dataRow.Cells(column.Ordinal), SourceTable.Rows(i + k)(column).ToString(), workbook, sheet)
                            End If
                        End If
                    Next
                    rowIndex = rowIndex + 1
                    dataRow = Nothing
                End If

            Next

            Dim colIndex As Integer
            For colIndex = 0 To SourceTable.Columns.Count - 1
                '不设置固定宽度，宽度自适应
                If colWidth Is Nothing Then
                    sheet.AutoSizeColumn(colIndex)
                Else
                    If Not colWidth.ContainsKey(colIndex) Then '自动
                        sheet.AutoSizeColumn(colIndex)
                    Else
                        sheet.SetColumnWidth(colIndex, colWidth(colIndex) * 256)
                    End If
                End If
            Next

            workbook.Write(ms)
            ms.Flush()
            ms.Position = 0

            sheet = Nothing
            titleRow = Nothing
            headerRow = Nothing
            sheetCount = sheetCount + 1
        Next

        workbook = Nothing

        'Dim Response = HttpContext.Current.Response
        'Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}{1}.xls", HttpContext.Current.Server.UrlEncode(title), DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss")))
        'Response.AddHeader("Set-Cookie", "fileDownload=true;path=/")
        'Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8")
        'Response.ContentType = "application/ms-excel;charset=UTF-8"
        'Response.BinaryWrite(ms.ToArray())

        'Response.Flush()
        'Response.End()
        'Response.Close()

        Dim re = ms.ToArray()
        ms.Close()
        ms.Dispose()

        Return re
    End Function


    ''' <summary>
    ''' DataTable导出,无标题,返回字节数 add by zhangrj 2022-10-18
    ''' 重写：Wangjh 20221124
    ''' </summary>
    ''' <param name="SourceTable">导出数据</param>
    ''' <param name="pigCol">需要填充图片的列</param>
    ''' <param name="colWidth">列宽指定每列的宽度,null：全部自动宽度，键值对中无对应索引列的key:自动宽度</param>
    ''' <remarks></remarks>
    Public Shared Function DataTableExportToExcel(ByVal SourceTable As DataTable, Optional ByVal colWidth As Dictionary(Of Integer, Integer) = Nothing, Optional ByVal pigCol As Integer() = Nothing) As Byte()

        If SourceTable.Rows.Count = 0 Then
            Return Nothing
        End If

        'PAGE_MAX_ROWS => 每个Sheet页最多能够显示的行数。Office 2003最多可显示65536行
        Const PAGE_MAX_ROWS As Integer = 65536

        Dim coloumsCount As Integer = SourceTable.Columns.Count()
        Dim workbook = New HSSFWorkbook()
        Dim ms = New MemoryStream()
        ' 单元格样式设置
        Dim style = workbook.CreateCellStyle()
        '水平对齐居中
        style.Alignment = HorizontalAlignment.Center
        '设置字体
        Dim Font = workbook.CreateFont()
        Font.FontName = "微软雅黑"
        style.SetFont(Font)
        '设置边框
        style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin
        style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin
        style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin
        style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin
        Dim headerCellStyle = workbook.CreateCellStyle()
        '居中显示
        headerCellStyle.Alignment = HorizontalAlignment.Center
        '设置边框
        headerCellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin
        headerCellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin
        headerCellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin
        headerCellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin
        '设置背景色
        headerCellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.LightGreen.Index
        headerCellStyle.FillPattern = FillPattern.SolidForeground
        '加粗
        Dim headerFont = workbook.CreateFont()
        headerFont.Boldweight = Short.MaxValue
        headerFont.FontName = "微软雅黑"
        headerCellStyle.SetFont(headerFont)

        Dim sheetCount As Integer = 1
        For i = 0 To SourceTable.Rows.Count - 1 Step (PAGE_MAX_ROWS - 1)
            Dim sheet As HSSFSheet = CType(workbook.CreateSheet("sheet" + sheetCount.ToString()), HSSFSheet)
            Dim row As HSSFRow = sheet.CreateRow(0)
            '添加表头
            For index = 0 To SourceTable.Columns.Count - 1
                row.CreateCell(index).SetCellValue(SourceTable.Columns(index).ColumnName)
                row.GetCell(index).CellStyle = headerCellStyle
            Next

            '填充内容
            '从第2行开始循环插入实际数据
            Dim rowIndex As Integer = 1

            Dim k As Integer
            For k = 0 To PAGE_MAX_ROWS - 1 - 1
                If (k + i) < SourceTable.Rows.Count Then
                    Dim dataRow As HSSFRow = CType(sheet.CreateRow(rowIndex), HSSFRow)
                    'Dim colIndex1 As Integer = 0
                    'For ci = 0 To SourceTable.Columns.Count - 1
                    '    If SourceTable.Rows(i + k)(ci).ToString().Contains("data:image/png;base64") Then
                    '        Dim sp = Regex.Split(SourceTable.Rows(i + k)(ci).ToString(), "<img src=\""", RegexOptions.IgnoreCase)
                    '        For Each item As String In sp
                    '            dataRow.CreateCell(colIndex1).SetCellValue("")
                    '            dataRow.Cells(colIndex1).CellStyle = style
                    '            If item.Contains("data:image/png;base64") Then
                    '                Dim itemsub = Regex.Split(item, "data:image/png;base64,", RegexOptions.IgnoreCase)
                    '                Dim sps = Regex.Split(itemsub(1), "\"">", RegexOptions.IgnoreCase)
                    '                Dim bt As Byte() = Convert.FromBase64String(sps(0))
                    '                Dim pictureIdx As Integer = workbook.AddPicture(bt, PictureType.JPEG)
                    '                Dim patriarch As HSSFPatriarch = CType(sheet.CreateDrawingPatriarch(), HSSFPatriarch)
                    '                Dim rowIndex1 As Integer = dataRow.Cells(colIndex1).RowIndex
                    '                Dim anchor As HSSFClientAnchor = New HSSFClientAnchor(0, 0, 0, 0, colIndex1, rowIndex1, colIndex1 + 1, rowIndex1 + 1)
                    '                Dim pict As HSSFPicture = CType(patriarch.CreatePicture(anchor, pictureIdx), HSSFPicture)
                    '                pict.Resize()
                    '                colIndex1 += 1
                    '                If sps.Length > 1 Then
                    '                    dataRow.CreateCell(colIndex1).SetCellValue("")
                    '                    dataRow.Cells(colIndex1).CellStyle = style
                    '                    dataRow.Cells(colIndex1).SetCellValue(sps(1))
                    '                    colIndex1 += 1
                    '                End If
                    '            Else
                    '                dataRow.Cells(colIndex1).SetCellValue(item)
                    '                colIndex1 += 1
                    '            End If
                    '        Next
                    '        sheet.AddMergedRegion(New CellRangeAddress(rowIndex, rowIndex, ci, colIndex1 - 1)) '合并单元格
                    '        Continue For
                    '    Else
                    '        dataRow.CreateCell(colIndex1).SetCellValue(SourceTable.Rows(i + k)(ci).ToString())
                    '        dataRow.Cells(colIndex1).CellStyle = style
                    '        colIndex1 += 1
                    '    End If
                    'Next

                    For Each column In SourceTable.Columns
                        dataRow.CreateCell(column.Ordinal).SetCellValue(SourceTable.Rows(i + k)(column).ToString())
                        dataRow.Cells(column.Ordinal).CellStyle = style
                        If pigCol IsNot Nothing Then '是否是图片列
                            If pigCol.Contains(column.Ordinal) And File.Exists(SourceTable.Rows(i + k)(column).ToString()) Then
                                dataRow.Cells(column.Ordinal).SetCellValue("")
                                AddPictureToCell(dataRow.Cells(column.Ordinal), SourceTable.Rows(i + k)(column).ToString(), workbook, sheet)
                            End If
                        End If
                    Next
                    rowIndex = rowIndex + 1
                    dataRow = Nothing
                End If

            Next

            '设置列宽
            For colIndex = 0 To SourceTable.Columns.Count - 1
                '不设置固定宽度，宽度自适应
                If colWidth Is Nothing Then
                    sheet.AutoSizeColumn(colIndex)
                Else
                    If Not colWidth.ContainsKey(colIndex) Then '自动
                        sheet.AutoSizeColumn(colIndex)
                    Else
                        sheet.SetColumnWidth(colIndex, colWidth(colIndex) * 256)
                    End If
                End If
            Next

            workbook.Write(ms)
            ms.Flush()
            ms.Position = 0

            sheet = Nothing
            sheetCount = sheetCount + 1
        Next


        Dim re = ms.ToArray()
        ms.Close()
        ms.Dispose()

        Return re
    End Function

    ''' <summary>
    ''' 将excel对象转化为Datatable add by zhangrj 2022-10-29
    ''' </summary>
    ''' <param name="workbook"></param>
    ''' <param name="startRowIndex">从第几行开始解析生成DataTable</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function ExcelImportToDataTable(ByVal workbook As IWorkbook, Optional ByVal startRowIndex As Integer = 0) As DataTable
        Dim sheet As ISheet = workbook.GetSheetAt(0)
        '将excel转为datatable
        Dim dt As New DataTable
        For index = 0 To sheet.GetRow(startRowIndex).Cells.Count - 1
            Dim value = GetCellValue(sheet.GetRow(startRowIndex).GetCell(index))
            If String.IsNullOrWhiteSpace(value) Then
                Exit For
            End If
            If Not dt.Columns.Contains(value) Then
                dt.Columns.Add(value)
            End If
        Next
        '循环取值，将excel内容填入datatable
        For index = startRowIndex + 1 To sheet.LastRowNum
            Dim row As IRow = sheet.GetRow(index)
            If row Is Nothing Then
                Exit For
            End If
            If row.Cells.Count = 0 Then
                Exit For
            End If
            If String.IsNullOrWhiteSpace(GetCellValue(row.GetCell(0))) Then
                Exit For
            End If
            Dim dr As DataRow = dt.NewRow
            For col = 0 To dt.Columns.Count - 1
                dr(col) = GetCellValue(row.GetCell(col))
            Next
            dt.Rows.Add(dr)
        Next
        Return dt
    End Function

    Public Shared Function ExcelSheetImportToDataTable(ByVal workbook As IWorkbook, Optional ByVal startSheetIndex As Integer = 0, Optional ByVal startRowIndex As Integer = 0) As DataTable
        Dim sheet As ISheet = workbook.GetSheetAt(startSheetIndex)
        '将excel转为datatable
        Dim dt As New DataTable
        For index = 0 To sheet.GetRow(startRowIndex).Cells.Count - 1
            Dim value = GetCellValue(sheet.GetRow(startRowIndex).GetCell(index))
            If String.IsNullOrWhiteSpace(value) Then
                Exit For
            End If
            If Not dt.Columns.Contains(value) Then
                dt.Columns.Add(value)
            End If
        Next
        '循环取值，将excel内容填入datatable
        For index = startRowIndex + 1 To sheet.LastRowNum
            Dim row As IRow = sheet.GetRow(index)
            If row Is Nothing Then
                Exit For
            End If
            If row.Cells.Count = 0 Then
                Exit For
            End If
            If String.IsNullOrWhiteSpace(GetCellValue(row.GetCell(0))) Then
                Exit For
            End If
            Dim dr As DataRow = dt.NewRow
            For col = 0 To dt.Columns.Count - 1
                dr(col) = GetCellValue(row.GetCell(col))
            Next
            dt.Rows.Add(dr)
        Next
        Return dt
    End Function
    ''' <summary>
    ''' 获取单元格值 add by zhangrj 20220901
    ''' </summary>
    ''' <param name="cell"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function GetCellValue(ByVal cell As ICell) As String
        If cell Is Nothing Then
            Return ""
        End If
        If cell.CellType = CellType.Formula Then
            cell.SetCellType(CellType.String)
        End If

        If cell.CellType = CellType.Numeric Then 'add by longb 2022-11-15 处理单元格时间取值
            If DateUtil.IsCellDateFormatted(cell) Then
                Return DateTime.FromOADate(cell.NumericCellValue).ToString("yyyy/MM/dd HH:mm:ss")
            End If
        End If

        If cell.IsMergedCell Then 'add by longb 2022-11-15 处理单元格合并取值
            For index = 0 To cell.Sheet.NumMergedRegions - 1
                Dim cellrange As CellRangeAddress = cell.Sheet.GetMergedRegion(index)
                If cell.ColumnIndex >= cellrange.FirstColumn And cell.ColumnIndex <= cellrange.LastColumn And cell.RowIndex >= cellrange.FirstRow And cell.RowIndex <= cellrange.LastRow Then
                    cell = cell.Sheet.GetRow(cellrange.FirstRow).GetCell(cellrange.FirstColumn)
                End If
            Next
        End If

        Return cell.ToString().Trim()
    End Function
    ''' <summary>
    ''' 添加照片到单元格
    ''' </summary>
    ''' <param name="cell"></param>
    ''' <param name="pigPath"></param>
    ''' <param name="workbook"></param>
    ''' <param name="sheet"></param>
    ''' <remarks></remarks>
    Public Shared Sub AddPictureToCell(ByVal cell As ICell, ByVal pigPath As String, ByVal workbook As HSSFWorkbook, ByVal sheet As HSSFSheet)
        Dim bytess As Byte() = System.IO.File.ReadAllBytes(pigPath)
        Dim pictureIdx As Integer = workbook.AddPicture(bytess, PictureType.JPEG)
        Dim patriarch As HSSFPatriarch = CType(sheet.CreateDrawingPatriarch(), HSSFPatriarch)
        Dim colIndex As Integer = cell.ColumnIndex
        Dim rowIndex As Integer = cell.RowIndex
        Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(pigPath)
        Dim strWidth As Integer = If(img.Width / 10 > 255, 255, img.Width / 10)

        If sheet.GetColumnWidth(colIndex) < 256 * strWidth Then
            sheet.SetColumnWidth(colIndex, 256 * strWidth)
        End If

        Dim anchor As HSSFClientAnchor = New HSSFClientAnchor(0, 0, 0, 0, colIndex, rowIndex, colIndex + 1, rowIndex + 1)
        Dim pict As HSSFPicture = CType(patriarch.CreatePicture(anchor, pictureIdx), HSSFPicture)
    End Sub

    ''' <summary>
    ''' 获取工作簿对象 'add by longb 2022-11-15
    ''' </summary>
    ''' <param name="filePath">文件地址</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function GetWorkbookObj(ByVal filePath As String) As IWorkbook
        Dim fileStream As FileStream = Nothing
        Try
            Dim IsXls = Path.GetExtension(filePath)
            '读取文件流
            fileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read)
            fileStream.Position = 0
            Dim workbook As IWorkbook
            If IsXls = ".xlsx" Then
                workbook = New NPOI.XSSF.UserModel.XSSFWorkbook(fileStream)
            Else
                workbook = New HSSFWorkbook(fileStream)
            End If
            fileStream.Close() '关闭文件流
            Return workbook
        Catch ex As Exception
            fileStream.Close() '关闭文件流
            Return Nothing
        End Try
    End Function
#End Region

    ''' <summary>
    ''' 合并图片和文字信息为一整个图片
    ''' </summary>
    ''' <param name="para">图片和文字队列</param>
    ''' <param name="fixedWidth">固定宽度</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function MerageImagsAndStrs(ByVal para As List(Of Object), ByVal fixedWidth As Integer) As String
        Dim resultPath As String = "", filaName As String = "image-" & DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fff")
        Dim fontSize As Integer = 10
        Dim fontPx As Integer = 7
        Dim bmpWidth As Integer = 0
        Dim bmpHeight As Integer = 20
        Dim addHeight As Integer = 20
        Dim addCount As Integer = 0

        If fixedWidth > 0 Then
            bmpWidth = fixedWidth
        End If

        Dim usedWidth As Integer = 0, usedHeight As Integer = 0

        For i As Integer = 0 To para.Count - 1
            Dim item = para(i)
            If item.[GetType]() = GetType(System.Drawing.Bitmap) Then
                Dim img As System.Drawing.Image = CType(item, System.Drawing.Image)

                If fixedWidth = 0 Then
                    bmpWidth += img.Width
                Else
                    usedHeight += addHeight
                    usedWidth = 0
                End If
            ElseIf item.[GetType]() = GetType(String) Then
                Dim strPixelLength As Integer = System.Text.Encoding.[Default].GetBytes(item.ToString()).Length * fontPx

                If fixedWidth = 0 Then
                    bmpWidth += strPixelLength
                Else

                    If usedWidth + strPixelLength <= fixedWidth Then
                        usedWidth += strPixelLength
                    Else
                        Dim addNum As Integer = CInt(Math.Ceiling((usedWidth + strPixelLength) / Single.Parse((fixedWidth).ToString())))

                        If addCount = 0 Then
                            usedHeight += addHeight * (addNum - 1)
                        Else
                            usedHeight += addHeight * (addNum)
                        End If
                        usedWidth = 0
                        addCount += 1
                    End If
                End If
            End If
        Next
        bmpHeight += usedHeight
        Dim objBmp As Bitmap = New Bitmap(bmpWidth, bmpHeight)
        Dim graphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(objBmp)
        graphics.Clear(Color.White)
        usedWidth = 0
        usedHeight = 0
        addCount = 0
        For Each item In para
            If item.[GetType]() = GetType(System.Drawing.Bitmap) Then
                Dim img As System.Drawing.Image = CType(item, System.Drawing.Image)

                If fixedWidth = 0 Then
                    graphics.DrawImage(img, usedWidth, 1, img.Width, 20)
                    usedWidth += img.Width
                Else

                    If usedWidth + img.Width + 1 <= fixedWidth Then
                        graphics.DrawImage(img, usedWidth, usedHeight, img.Width, 20)
                        usedWidth += img.Width + 1
                    Else
                        usedHeight += addHeight
                        usedWidth = img.Width + 1
                        graphics.DrawImage(img, 0, usedHeight, img.Width, 20)
                    End If
                End If
            ElseIf item.[GetType]() = GetType(String) Then
                Dim strPixelLength As Integer = System.Text.Encoding.[Default].GetBytes(item.ToString()).Length * fontPx

                If fixedWidth = 0 Then
                    graphics.DrawString(item.ToString(), New System.Drawing.Font("宋体", fontSize), New System.Drawing.SolidBrush(System.Drawing.Color.Red), New System.Drawing.Point(usedWidth, 0))
                    usedWidth += strPixelLength
                Else

                    For Each s In item.ToString()
                        Dim sl As Integer = System.Text.Encoding.[Default].GetBytes(s.ToString()).Length * fontPx

                        If usedWidth + sl + 1 <= fixedWidth Then
                            graphics.DrawString(s.ToString(), New System.Drawing.Font("宋体", fontSize), New System.Drawing.SolidBrush(System.Drawing.Color.Red), New System.Drawing.Point(usedWidth, usedHeight))
                            usedWidth += sl
                        Else
                            usedWidth = 0
                            usedHeight += addHeight
                            graphics.DrawString(s.ToString(), New System.Drawing.Font("宋体", fontSize), New System.Drawing.SolidBrush(System.Drawing.Color.Red), New System.Drawing.Point(usedWidth, usedHeight))
                            usedWidth += sl
                        End If
                    Next
                End If
            End If
        Next
        resultPath = ConfigurationManager.AppSettings("ImageTempSavePath") + filaName
        objBmp.Save(resultPath, System.Drawing.Imaging.ImageFormat.Jpeg)
        graphics.Dispose()
        Return resultPath
    End Function

    ''' <summary>
    ''' 将字节数组转化为文件
    ''' </summary>
    ''' <param name="bys"></param>
    ''' <param name="strPath"></param>
    ''' <remarks></remarks>
    Public Shared Sub ParseBytesToFile(ByVal bys As Byte(), ByVal strPath As String)
        Dim fs = New FileStream(strPath, System.IO.FileMode.Create)
        Dim Buffer = bys
        fs.Write(Buffer, 0, Buffer.Length)
        fs.Flush()
        fs.Close()
    End Sub

    ''' <summary>
    ''' 删除文件 'add by longb 2022-11-15
    ''' </summary>
    ''' <param name="filePath">文件地址</param>
    ''' <remarks></remarks>
    Public Shared Sub DeleteFile(ByVal filePath As String)
        If File.Exists(filePath) Then
            File.Delete(filePath)
        End If
    End Sub

#Region "实测值提取"
    'add by longb 2023-02-26
    Public Function GetCheckPointValue(ByVal content As String) As List(Of Dictionary(Of String, String))
        Dim List As New List(Of Dictionary(Of String, String))
        Dim sy As Array = GetSubStrCountInStr(content, "<Image>", 0)
        Dim ey As Array = GetSubStrCountInStr(content, "</Image>", 0)
        For i = 0 To sy.Length - 1
            Dim baseValue As String = String.Empty, upValue = String.Empty, dwValue = String.Empty
            Dim ImageContent As String = content.Substring(sy(i) + 7, ey(i) - (sy(i) + 7)) '截取<Image>里面的内容
            If (ImageContent.Contains("<T")) Then '含有基准值、上下限值情况
                baseValue = System.Text.RegularExpressions.Regex.Replace(Split(ImageContent, "<")(0), "[^\d.\d]", "")
                upValue = Split(Split(ImageContent, "<")(1), "!")(0).Replace("T", "")
                dwValue = Split(Split(ImageContent, "<")(1), "!")(1).Replace(">", "")
            End If
            If (ImageContent.Contains("<H")) Then '只含基准值，上限
                baseValue = System.Text.RegularExpressions.Regex.Replace(Split(ImageContent, "<")(0), "[^\d.\d]", "")
                upValue = Split(ImageContent, "<")(1).Replace("H>", "").Replace("</H>", "")
            End If

            If (ImageContent.Contains("<L")) Then '只含基准值，下限
                baseValue = System.Text.RegularExpressions.Regex.Replace(Split(ImageContent, "<")(0), "[^\d.\d]", "")
                dwValue = Split(ImageContent, "<")(1).Replace("L>", "").Replace("</L>", "")
            End If


            If (ImageContent.Contains("<R")) Then  '去除材料
                baseValue = ImageContent.Replace("<R>", "").Replace("</R>", "")
            End If

            If (ImageContent.Contains("√")) Then '指定加工方法
                baseValue = Split(ImageContent.Replace("<√>", "").Replace("</√>", ""), "<")(0)
                upValue = Split(Split(ImageContent.Replace("<√>", "").Replace("</√>", ""), "<")(1), ",")(0)
                dwValue = Split(Split(ImageContent.Replace("<√>", "").Replace("</√>", ""), "<")(1), ",")(1).Replace(">", "")
            End If

            If (Not String.IsNullOrWhiteSpace(baseValue) Or Not String.IsNullOrWhiteSpace(upValue) Or Not String.IsNullOrWhiteSpace(dwValue)) Then
                Dim dic As New Dictionary(Of String, String)
                dic.Add("baseValue", baseValue)
                dic.Add("upValue", upValue)
                dic.Add("dwValue", dwValue)
                List.Add(dic)
            End If
        Next
        Return List
    End Function

    Public Function GetSubStrCountInStr(ByVal str As String, ByVal substr As String, ByVal StartPos As Integer) As Array
        Dim foundPos As Integer = -1
        Dim count As Integer = 0
        Dim foundItems As New List(Of Integer)
        Do
            foundPos = str.IndexOf(substr, StartPos)
            If (foundPos > -1) Then
                StartPos = foundPos + 1
                count = count + 1
                foundItems.Add(foundPos)
            End If
        Loop While (foundPos > -1 And StartPos < str.Length)
        Return foundItems.ToArray()
    End Function
#End Region


End Class